﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Web.Oauth2.impl
{
    public class WechatConnector : OauthConnector
    {
        public WechatConnector(String appkey, String appSecret) : base(appkey, appSecret)
        {
            Type = OauthType.wechat;
        }
        /// <summary>
        /// https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1419316505
        /// </summary>
        /// <param name="state"></param>
        /// <returns></returns>
        protected override String CreateAuthorizeUrl(String state)
        {

            // https://open.weixin.qq.com/connect/qrconnect?
            // appid=APPID
            // &redirect_uri=REDIRECT_URI
            // &response_type=code
            // &scope=SCOPE
            // &state=STATE#wechat_redirect
            StringBuilder urlBuilder = new StringBuilder("https://open.weixin.qq.com/connect/qrconnect?");
            urlBuilder.Append("response_type=code");
            urlBuilder.Append("&scope=snsapi_login");
            urlBuilder.Append("&appid=" + ClientId);
            urlBuilder.Append("&redirect_uri=" + RedirectUri);
            urlBuilder.Append("&state=" + state);
            urlBuilder.Append("#wechat_redirect");

            return urlBuilder.ToString();
        }

        protected override OauthUser GetOauthUser(String code)
        {
            //var jObject = JObject.Parse(GetAccessToken(code));
            AccessToken a= GetAccessToken(code);
            String accessToken = a.access_token;
            String openId = a.openid;

            // https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
            String url = "https://api.weixin.qq.com/sns/userinfo?" + "access_token=" + accessToken + "&openid=" + openId;

            String httpString = HttpGet(url);
            if (String.IsNullOrEmpty(httpString))
            {
                return null;
            }

            /**
             * { "openid":"OPENID", "nickname":"NICKNAME", "sex":1,
             * "province":"PROVINCE", "city":"CITY", "country":"COUNTRY",
             * "headimgurl":
             * "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
             * "privilege":[ "PRIVILEGE1", "PRIVILEGE2" ], "unionid": "
             * o6_bmasdasdsad6_2sgVt7hMZOPfL" }
             */
            OauthUser user = new OauthUser();

            var jObject = JObject.Parse(httpString);
            user.Avatar= jObject["headimgurl"].ToString();
            user.Nickname= jObject["nickname"].ToString();
            user.OpenId=openId;
            int sex = jObject["sex"].ToObject<int>();
            user.Gender=(sex == 1 ? "male" : "female");

            user.Source=Type.ToString();

            return user;
        }

        public override AccessToken GetAccessToken(String code)
        {

            // https://api.weixin.qq.com/sns/oauth2/access_token?
            // appid=APPID
            // &secret=SECRET
            // &code=CODE
            // &grant_type=authorization_code
            StringBuilder urlBuilder = new StringBuilder("https://api.weixin.qq.com/sns/oauth2/access_token?");
            urlBuilder.Append("grant_type=authorization_code");
            urlBuilder.Append("&appid=" + ClientId);
            urlBuilder.Append("&secret=" + ClientSecret);
            urlBuilder.Append("&code=" + code);

            String url = urlBuilder.ToString();

            String httpString = HttpGet(url);

            /**
             * { "access_token":"ACCESS_TOKEN", "expires_in":7200,
             * "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE",
             * "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL" }
             */
            return JsonConvert.DeserializeObject<AccessToken>(httpString);
        }

        public override AccessToken RefreshAccessToken(string refresh_token)
        {
            throw new NotImplementedException();
        }
    }
}
